import 'package:im_app/im/util/MapUtil.dart';
import 'package:sqflite/sqflite.dart';

import '../pojo/Enums.dart';
import '../pojo/UiPojo.dart';
import '../util/ImSingleton.dart';
import 'BaseDao.dart';
import 'ImGroupDao.dart';
import 'ImUserDao.dart';

class ImUserAndGroupDao extends BaseDao {

  Future<List<ImUserAndGroup>> getNewByStartId(String userId, int start, int size) async {
    Database? database = getDatabase(); //ImSingleton.getInstance()?.dataBase;
    var sql = '''select * from (
        select u.id id, u.userId code, u.userName name, u.firstLetter firstLetter, 'user' as type from im_user u 
        UNION
        select g.id id, g.code code, g.name name, g.firstLetter firstLetter, 'group' as type from im_group g
        ) t order by firstLetter, id limit $start, $size''';
    List<Map<String, Object?>>? list = await database?.rawQuery(sql);
    List<ImUserAndGroup> results = list != null ? list.map((map)=>_toImUserGroup(map)).toList() : [];
    if (results.isNotEmpty) {
      var userDao = ImUserDao();
      var groupDao = ImGroupDao();
      for (var userAndGroup in results) {
        if (userAndGroup.type == UserAndGroupType.user) {
          userAndGroup.user = await userDao.getByUserId(userAndGroup.code);
        } else {
          userAndGroup.group = (await groupDao.getByCodeAndUserId(userAndGroup.code, userId!));
        }
      }
    }
    return results;
  }

  ImUserAndGroup _toImUserGroup(Map<String, dynamic> map) {
    var userGroup = ImUserAndGroup(
      id: MapUtil.getInt(map, 'id'),
      code: MapUtil.getString(map, 'code'),
      name: MapUtil.getString(map, 'name'),
      firstLetter: MapUtil.getStringOrNull(map, 'firstLetter')??'#',
      type: UserAndGroupType.ofName(MapUtil.getString(map, "type"))
    );
    return userGroup;
  }
}